from flask import Blueprint,request
from .db import DB
import time
import datetime
import hashlib
import requests
# fengbiao
myMD = "642c5b3ccade42b0f48eceebc25e5cf5"
license = Blueprint('license', __name__)
db = DB()
db.open()

@license.route("/",methods=['POST','GET'])
def license_api():
    if request.method == 'POST':
        if not request.form:
            return "MD码错误", 100
        if request.form["api_key"] != myMD:
            return "MD码错误", 100
        return 新增license(request.form.get("expiration_date") or 30)

    if request.method == 'GET':
        if request.args.get('api_key') != myMD and not request.args.get('api_key'):
            return "校验码错误", 200

        if not request.args.get('card_key'):
            return "请输入正确CODE" , 110
        return 注册license(request, request.args)

@license.route("/unbind",methods=['POST'])
def unbind_api():
    if not request.form:
        return "MD码错误", 100
    if request.form["api_key"] != myMD:
        return "MD码错误", 100
    return 解绑license(request,request.form)



def 新增license(expiration_date):
    card_key = md5加密()
    # db.ping(reconnect=True)
    # 获取总数
    sql = "SELECT COUNT(*) FROM list"
    try:
        idx =db.execute_select(sql)[0]['COUNT(*)']
    except ValueError  as e:
        print(f"查询失败: {e}")
        return "查询失败", 110

    # 新增
    sql = "INSERT INTO list (idx, card_key, c_type, expiration_date, card_type, create_time) VALUES (%s, %s, %s, %s, %s, %s)"
    try:
        # cursor.execute(sql, (int(idx) + 1, card_key, "HJ", expiration_date, "time", 获取当前时间()))
        db.execute_insert(sql, (int(idx) + 1, card_key, "HJ", expiration_date, "time", 获取当前时间()))
    except ValueError  as e:
        print(f"新增失败: {e}")
        return "新增失败", 110
    return {'msg': '新增成功', 'key': card_key}, 200

def 注册license(req, data):
    device_id = data['device_id']
    getLicense = 查询license(data)

    # 注册使用
    if not getLicense['register_time']:
        print(req.remote_addr)
        ip_addre = get_ip_location(req.remote_addr)
        sql = "UPDATE list SET register_time = %s, expire_time = %s, device_id = %s, ip = %s, ip_addre = %s WHERE id = %s and card_key = %s"
        expire_time = 过期时间(getLicense['expiration_date'])
        try:
            # cursor.execute(sql, (获取当前时间(), expire_time, device_id,req.remote_addr,f"{ip_addre['regionName']}/{ip_addre['city']}",
            #     getLicense['id'], getLicense['card_key']))
            db.execute_update(
                sql, (获取当前时间(), expire_time, device_id, req.remote_addr,
                      f"{ip_addre['regionName']}/{ip_addre['city']}",
                      getLicense['id'], getLicense['card_key'])
            )
            # return {"code": 200, "expire_time": expire_time, "expiration_date": getLicense["expiration_date"]}, 200
        except ValueError  as e:
            print(f"查询失败: {e}")
            return "查询失败", 110
    elif getLicense['device_id']:
        if device_id != getLicense['device_id']:
            return {
                "code": 100,
                "msg":"该卡密已绑定，请解绑"
            }, 200

    return {"code": 200,
            "data":
                {
                    "card_key": getLicense['card_key'],
                    "device_id": getLicense['device_id'] or device_id,
                    "expire_time": getLicense["expire_time"] or expire_time,
                    "expiration_date": getLicense["expiration_date"],
                    "card_type": getLicense["card_type"],
                }
            }, 200

def 解绑license(req,data):
    getLicense = 查询license(data)
    if not getLicense or not getLicense['device_id']:
        return {
            "code": 100,
            "msg": "卡密未注册/错误"
        }, 200
    sql="UPDATE list set device_id = %s WHERE id = %s and card_key = %s"
    db.execute_update(sql, ("",getLicense['id'], getLicense['card_key']))
    return {
        "code": 200,
        "msg": "解绑成功"
    }, 200

def 查询license(data):
    card_key,c_type = data['card_key'],data['c_type']
    if not card_key or not c_type:
        return {
            "code": 100,
            "msg":"错误查询"
        }, 200
    sql = "SELECT * FROM list WHERE card_key = (%s) and c_type = (%s)"
    try:
        getLicense = db.execute_select(sql, (card_key, c_type))[0]
        if not getLicense:
            return "code错误", 110
    except ValueError  as e:
        print(f"查询失败: {e}")
        return "查询失败", 110
    return  getLicense



def get_ip_location(ip):
    url = f"http://ip-api.com/json/{ip}"  # API地址，ip是你要查的IP
    response = requests.get(url)  # 发送请求，获取返回数据
    if response.status_code == 200:  # 200表示请求成功
        data = response.json()  # 把数据转成字典格式
        return data  # 返回查询结果
    else:
        print("查询失败，可能是网络问题或IP不对！")
        # 日志.显示内容到界面("get_ip_location", f"查询失败，可能是网络问题或IP不对！")
        return None
def get_ip_location(ip):
    url = f"http://ip-api.com/json/{ip}"  # API地址，ip是你要查的IP
    response = requests.get(url)  # 发送请求，获取返回数据
    if response.status_code == 200:  # 200表示请求成功
        data = response.json()  # 把数据转成字典格式
        return data  # 返回查询结果
    else:
        print("查询失败，可能是网络问题或IP不对！")
        # 日志.显示内容到界面("get_ip_location", f"查询失败，可能是网络问题或IP不对！")
        return None
def md5加密():
    timestamp = time.time()
    m = hashlib.md5(str(timestamp).encode()).hexdigest()
    return m
def 获取当前时间():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
def 过期时间(day):
    return (datetime.datetime.now()+datetime.timedelta(days=day)).strftime("%Y-%m-%d %H:%M:%S")
